console.log(`
   
   ▒█████ ██   ██  ▄████▄   ██ ▄█▀       ██████╗ ██╗   ██╗ ██████╗
  ▒██   ▒███  ▓██▒▒██▀ ▀█   ██▄█▒        ██╔══██╗██║   ██║██╔════╝
  ▒█████░▓██  ▒██░▒▓█    ▄ ▓███▄░        ██████╔╝██║   ██║██║  ███╗
  ░██▒  ░▓██  ░██░▒▓▓▄ ▄██▒▓██ █▄        ██╔══██╗██║   ██║██║   ██║
  ░██░   ▒▒██████ ▒ ▓███▀ ░▒██▒ █▄       ██████╔╝╚██████╔╝╚██████╔╝
   ▒ ░   ░▒▓▒ ▒ ▒ ░ ░▒ ▒  ░▒ ▒▒ ▓▒       ╚═════╝  ╚═════╝  ╚═════╝
   ░     ░░▒░ ░ ░   ░  ▒   ░ ░▒ ▒░
   ░ ░    ░░░ ░ ░ ░        ░ ░░ ░
            ░     ░ ░      ░  ░

`);

/*
	@filename: main.js
	@description: 实现主窗口的交互事件以及主要功能
	@author: HUIB.TOP
	@version：v1.0
	@date：2023/9/24
*/

document.onselectstart = function() {
	return false;
}

require.config({
	paths: {
		"jquery": ["res/static/js/jquery-1.9.1.min"],
		"ior": ["res/static/js/ior"],
		"layui": ["res/static/layui/layui"],
		"GHAPI": ["res/js/api"]
	},
	shim: {
		"ior": {
			exports: "ior"
		},
		"layui": {
			exports: "layui"
		},
		"GHAPI": {
			exports: "GHAPI"
		},
	}
});

require(["jquery", "ior", "layui", "GHAPI"], function($, iro, layui, GHAPI) {
	
	$(function() {
		// 加载窗口动画
		
		$("body").addClass("fade_in");
		
		// 窗口移动
		$(".win_title .win_drag").mousedown(async function() {
			GHAPI.Win.hitCaption();
		});

		// 关闭窗口
		$(".win_btn.close").click(async function() {
			$(".win_from").fadeOut(300, function() {
				GHAPI.Win.close();
			});
		});

		// 最小化
		$(".win_btn.min").click(async function() {
			GHAPI.Win.hitMin();
		});


		/*
			加载配置文件
		*/
		GHAPI.Win.read_Config("/web/res/lib/set.json", true).then(function(config) {
			var old_color = ['#ffffff', '#ffffff', '#ffffff', '#ffffff', '#ffffff', '#ffffff', '#ffffff'];
			var Collect = [
				'#ffffff', '#ffffff', '#ffffff', '#ffffff', '#ffffff', '#ffffff', '#ffffff',
				'#ffffff', '#ffffff', '#ffffff', '#ffffff', '#ffffff', '#ffffff', '#ffffff'
			];

			// 加载历史颜色
			(function() {
				if (config.set.Other.Save_Old_Color == 'on') {
					if (config.color.History.length > 6) {
						old_color = config.color.History;
						for (let i = 0; i < old_color.length; i++) {
							$("#old_color li").eq(i).css("background-color", old_color[i]);
						}
					}
				}
			})();

			// 加载色板颜色
			(function() {
				if (config.color.Collect.length > 13) {
					Collect = config.color.Collect;
					for (let a = 0, b = 0; a < Collect.length; a++) {
						if (a < 7) {
							$("#Collect>.card1>li").eq(a).css("background-color", Collect[a]);
						} else {
							b++;
							$("#Collect>.card2>li").eq(b - 1).css("background-color", Collect[a - 1]);
						}
					}
				}
			})();

			create_Main(old_color, Collect, config);
			create_Pantone();
		});
	});


	/* Main 主界面事件 */
	function create_Main(old_color, Collect, config) {

		/*
			导航栏事件 
		*/
		$(".win_nav ul li").click(async function() {
			var page = $(this).attr("page");

			if (page == 1 || page == 2 || page == 4) {
				$(".win_nav ul li").removeClass("sel");
				$(this).addClass("sel");

				$(".page").hide();
				$(".page_" + page).show();
			}


			/*
				进入拾色模式
				这里主要调用浏览器EyeDropper的API，可能存在兼容性问题
			*/
			if (page == 3) {

				if (window.EyeDropper) {
					const eyeDropper = new EyeDropper();
					const res = await eyeDropper.open();

					colorPicker1.colors[0].set(res.sRGBHex);

					// 添加历史颜色
					Add_old_color(colorPicker1.color);
				} else {
					layer.msg("无法打开拾色模式");
				}
			}

			if (page == 5) {
				// 打开设置窗口
				aardio.win_open("set");
			}
		});



		// 创建 色轮1 组件
		var component = iro.ui.Wheel;
		if(config.set.Function.colorDisc == 2){
			component = iro.ui.Box;
			$(".color_piker").addClass("piker_box");
		}
		
		var colorPicker1 = iro.ColorPicker("#picker_1", {
			sliderSize: 14,
			handleRadius: 6,
			padding: 0,
			margin: 16,
			width: $("#picker_1").width(),
			color: "#fff",
			layout: [
				// 创建色轮
				{
					component: component
				}
			]
		});

		// 创建 色轮2 组件
		var colorPicker2 = new iro.ColorPicker("#picker_2", {
			sliderSize: 14,
			handleRadius: 6,
			padding: 0,
			margin: 14,
			width: $("#picker_2").width(),
			color: "#fff",
			layout: [
				// 创建色轮
				{
					component: component
				}
			]
		});


		// 创建滑块组件
		var colorPicker3 = new iro.ColorPicker(".piker_h", {
			sliderSize: 10,
			handleRadius: 8,
			padding: 0,
			margin: 38,
			width: $(".piker_h").width(),
			color: "#fff",
			layout: [
				// 创建色轮
				{
					component: iro.ui.Slider,
					options: {
						sliderType: 'hue'
					}
				},
				{
					component: iro.ui.Slider,
					options: {
						sliderType: 'saturation'
					}
				},
				{
					component: iro.ui.Slider,
					options: {
						sliderType: 'value'
					}
				}
			]
		});


		(function() {
			// 色轮1事件
			colorPicker1.on('color:change', function(color) {
				let hex = color.hexString.toUpperCase();

				if (color.index === 0) {
					$(".page_1 .color_piker .color_hex").val(hex);
					$(".page_1 .color_piker .color_1").css("background-color", hex);

					colorPicker2.colors[0].set(hex);
					Add_old_color2();
				}
			});
			colorPicker1.on('input:start', function(color) {

			});
			colorPicker1.on('input:end', function(color) {
				Add_old_color(color);
			});


			// 色轮2事件
			colorPicker2.on('color:change', function(color) {
				let hex = color.hexString.toUpperCase();
				if (color.index === 0) {
					$(".page_2 .color_piker .color_hex").val(hex);
					$(".page_2 .color_piker .color_1").css("background-color", hex);
					colorPicker1.colors[0].set(hex);
					colorPicker3.colors[0].set(hex);
					Add_old_color2();
				}

			});
			colorPicker2.on('input:start', function(color) {

			});
			colorPicker2.on('input:end', function(color) {
				Add_old_color(color);
			});


			// 滑块事件
			colorPicker3.on('color:change', function(color) {
				let hex = color.hexString.toUpperCase();
				if (color.index === 0) {
					colorPicker2.colors[0].set(hex);
					Add_old_color2();
				}
			});
			colorPicker3.on('input:start', function(color) {

			});
			colorPicker3.on('input:end', function(color) {
				Add_old_color(color);
			});

		})();

		// 添加历史颜色
		function Add_old_color(color) {
			let hex = color.hexString.toUpperCase();
			old_color.unshift(hex);
			old_color = old_color.slice(0, 7);

			for (let i = 0; i < 7; i++) {
				$("#old_color li").eq(i).css("background-color", old_color[i]);
			}

			// 保存历史颜色
			GHAPI.Win.read_Config("/web/res/lib/set.json", true).then(function(config) {
				if (config.set.Other.Save_Old_Color == 'on') {
					config.color.History = old_color;
					GHAPI.Win.write_Config("/web/res/lib/set.json", config, true);
				}
			});
		};

		function Add_old_color2() {
			let hex, rgb, cmyk;

			hex = $(".page_1 .color_piker .color_1").css("background-color");
			rgb = hex.slice(4, hex.length - 1).replace(/\s/g, '').split(",");
			rgb = {
				r: Number(rgb[0]),
				g: Number(rgb[1]),
				b: Number(rgb[2])
			};
			cmyk = GHAPI.rgb2cmyk(rgb);
			rgb = GHAPI.cmyk2rgb(cmyk);
			rgb = "rgb(" + rgb.r + ", " + rgb.g + ", " + rgb.b + ")"

			$(".page_1 .color_piker .color_2,.page_2 .color_piker .color_2").css("background-color", rgb);
		};


		// HEX值事件
		(function() {
			$(".color_piker .color_hex").click(function() {
				this.selectionStart = 0;
				this.selectionEnd = $(this).val().length;
			});
			$(".color_piker .color_hex").on("input", function() {
				var str = $(this).val().slice(1, 7);
				var hex = "";

				if (str.length == 3) {
					str = str + str;
				}

				if (str.length == 6) {
					colorPicker1.colors[0].set("#" + str);
					Add_old_color(colorPicker1.color);
				}
			});

		})();


		(function() {
			let times, hex1, hex2;

			// 页面1 复制颜色到剪切板
			$(".page_1 .color_card .card li, .page_1 .color_piker .color").click(function() {
				hex1 = colorPicker1.colors[0].hexString;
				hex2 = $(this).css("background-color");

				clearTimeout(times);

				times = setTimeout(function() {
					GHAPI.Win.read_Config("/web/res/lib/set.json", true).then(function(config) {
						let colorSpace = config.set.Function.colorSpace;

						colorPicker1.colors[0].set(hex2);
						if (colorSpace == 1) {
							/* 复制HEX */
							hex2 = colorPicker1.colors[0].hexString.toUpperCase();

						} else if (colorSpace == 2) {
							/* 复制RGB */
							hex2 = colorPicker1.colors[0].rgbString.toUpperCase();

						} else if (colorSpace == 3) {
							/* 复制HSL */
							hex2 = colorPicker1.colors[0].hslbString.toUpperCase();

						} else if (colorSpace == 4) {
							/* 复制CMYK */
							hex2 = colorPicker1.colors[0].rgbString.toUpperCase();
							let CMYK = GHAPI.rgb2cmyk(colorPicker1.colors[0].rgb);
							hex2 = "CMYK(" + CMYK.c + ", " + CMYK.m + ", " + CMYK.y + ", " + CMYK.k + ")";
						}
						colorPicker1.colors[0].set(hex1);
						GHAPI.GH_copy(hex2);
					});
				}, 200);
			});

			// 页面1 将当前颜色添加到色轮
			$(".page_1 .color_card .card li, .page_1 .color_piker .color").dblclick(function() {
				clearTimeout(times);
				colorPicker1.colors[0].set(hex2);
			});
		})();






		/*
			右键菜单
		*/

		layui.use(function() {
			var dropdown = layui.dropdown;
			var util = layui.util;
			dropdown.render({
				elem: '.page_1 .color_card .card li, .page_1 .color_piker .color, .page_2 .color_piker .color',
				trigger: 'contextmenu',
				isAllowSpread: false,
				style: 'width: 130px',
				data: [{
						title: '添加到常用',
						id: 'add_palette'
					}, {
						title: '查找潘通色',
						id: 'seach_pantone'
					},

					{
						type: '-'
					},
					{
						title: '复制当前色号',
						id: 'copy_hex'
					},
					{
						title: '复制其他色号',
						child: [{
								title: '复制 HEX',
								id: 'copy_hex'
							},
							{
								title: '复制 RGB',
								id: 'copy_rgb'
							}, {
								title: '复制 HSL',
								id: 'copy_hsl'
							},
							{
								title: '复制 CMYK',
								id: 'copy_cmyk'
							},
						]
					},
				],

				// 点击菜单触发
				click: function(obj, othis) {
					let color1 = colorPicker1.colors[0].hexString;
					let color2 = this.elem.css("background-color");
					colorPicker1.colors[0].set(color2);

					let hex = colorPicker1.colors[0].hexString.toUpperCase();
					let rgb = colorPicker1.colors[0].rgbString.toUpperCase();
					let hsl = colorPicker1.colors[0].hslString.toUpperCase();
					let cmyk = GHAPI.rgb2cmyk(colorPicker1.colors[0].rgb);
					cmyk = "CMYK(" + cmyk.c + ", " + cmyk.m + ", " + cmyk.y + ", " + cmyk.k + ")";

					if (obj.id === 'add_palette') {
						add_Collect();
					} else if (obj.id === 'copy_rgb') {
						GHAPI.GH_copy(rgb);
					} else if (obj.id === 'copy_hsl') {
						GHAPI.GH_copy(hsl);
					} else if (obj.id === 'copy_cmyk') {
						GHAPI.GH_copy(cmyk);
					} else if (obj.id === 'seach_pantone') {
						$(".win_nav li[page=4]").click();
						$(".page_4 .pantone_seach input").val(hex);
						$(".page_4 .pantone_seach button").click();
					}
					colorPicker1.colors[0].set(color1);

					function add_Collect() {
						Collect.unshift(hex);
						Collect = Collect.slice(0, 14);
						for (let a = 0, b = 0; a < Collect.length; a++) {
							if (a < 7) {
								$("#Collect>.card1>li").eq(a).css("background-color", Collect[a]);
							} else {
								b++;
								$("#Collect>.card2>li").eq(b - 1).css("background-color", Collect[a - 1]);
							}
						}

						// 保存色板颜色
						GHAPI.Win.read_Config("/web/res/lib/set.json", true).then(function(config) {
							config.color.Collect = Collect;
							GHAPI.Win.write_Config("/web/res/lib/set.json", config, true);
						});
					}
				}
			});
		});
	};



	/*
		潘通色卡页 事件
	*/
	function create_Pantone() {

		// 加载流行色
		var json = GHAPI.api.get_popular_colors();
		var data = json.data;
		var rgb, cmyk, pantone, hex;
		$(".page_4 .pantone").html("");
		for (var i_1 = 0; i_1 < data.length; i_1++) {

			if (i_1 > 9) {
				break;
			}

			var Colors = data[i_1].Colors;
			for (var i_2 = 0; i_2 < Colors.length; i_2++) {
				rgb = Colors[i_2].RGB_R + "," + Colors[i_2].RGB_G + "," + Colors[i_2].RGB_B;
				cmyk = Colors[i_2].CMYK_C + "," + Colors[i_2].CMYK_M + "," + Colors[i_2].CMYK_Y + "," + Colors[i_2].CMYK_K;
				hex = Colors[i_2].Hex;
				pantone = Colors[i_2].Code;

				$(".page_4 .pantone").append(`<div class="card" rgb="` + rgb + `" cmyk="` + cmyk + `" pantone="` + pantone + `" hex="` + hex + `" style="background-color:` + hex + `"></div>`);
			}
		}


		// 展开色卡
		$(document).on("click", ".page_4 .pantone .card", function() {
			$(".page_4 .pantone").toggleClass("sel");
			$(".page_4 .pantone2").toggleClass("sel");

			let pantone = $(this).attr("pantone");
			let rgb = $(this).attr("rgb");
			let hex = $(this).attr("hex");
			let cmyk = $(this).attr("cmyk");

			$(".page_4 .pantone2 .code").text(pantone);
			$(".page_4 .pantone2 .rgb").text(rgb);
			$(".page_4 .pantone2 .hex").text(hex);
			$(".page_4 .pantone2 .cmyk").text(cmyk);


			// 根据色卡背景色明度调整字体颜色
			let hsl = GHAPI.rgb2hsl(rgb);
			let [h, s, l] = hsl.match(/\d+/g);
			let is_light = false;

			is_light = (l > 60)

			if (is_light == false) {
				$(".page_4 .pantone2").css({ "color": "#FFFFFF", "font-weight": "normal" });
			} else {
				$(".page_4 .pantone2").css({ "color": "#1c1c23", "font-weight": "bold" });
			}


			console.log(h, s, l, hsl);
			$(this).toggleClass("sel");
		});

		// 展开色卡复制色值
		$(".pantone2 p .rgb").click(function() {
			GHAPI.GH_copy("rgb(" + $(this).text() + ")");
		});
		$(".pantone2 p .cmyk").click(function() {
			GHAPI.GH_copy("cmyk(" + $(this).text() + ")");
		});
		$(".pantone2 p .hex").click(function() {
			GHAPI.GH_copy($(this).text());
		});



		// 搜索潘通
		$(".page_4 .pantone_seach button").click(function() {
			var color = $(".page_4 .pantone_seach input").val();
			var json, list, rgb, cmyk, pantone, hex;
			if (color == "") {
				layer.msg("请输入你需要搜索的色号");
				return;
			}

			json = GHAPI.api.seach_pantone(color);
			$(".page_4 .pantone").html("");

			if (json.data.list == null || json.data.list.length == null) {
				$(".page_4 .pantone").html("没有找到相应的颜色");
				return;
			}
			if (json.data.list.length < 1) {
				return;
			}


			list = json.data.list;
			for (var i = 0; i < list.length; i++) {

				rgb = list[i].ColorlibraryItems[0].RGB_R + "," + list[i].ColorlibraryItems[0].RGB_G + "," + list[i].ColorlibraryItems[0].RGB_B;
				cmyk = list[i].ColorlibraryItems[0].CMYK_C + "," + list[i].ColorlibraryItems[0].CMYK_M + "," + list[i].ColorlibraryItems[0].CMYK_Y + "," + list[i].ColorlibraryItems[0].CMYK_K;
				hex = list[i].ColorlibraryItems[0].Hex;
				pantone = list[i].ColorlibraryItems[0].Code;

				$(".page_4 .pantone").append(`<div class="card" rgb="` + rgb + `" cmyk="` + cmyk + `" pantone="` + pantone + `" hex="` + hex + `" style="background-color:` + hex + `"></div>`);
			}
		});
	}
});